﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Data;
using WMS.FC.Domain.DomainObject.Menu;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.PersistenceObject.System;
using WMS.FC.Domain.Repository;
using WMS.FC.Domain.Service.System.Interface;

namespace WMS.FC.Domain.Service.System
{
    public class GetDictionaryService : ServiceBase, IGetDictionaryService
    {
        protected readonly IMenuRepository menuRepository;
        protected readonly ISystemRepository systemRepository;

        public GetDictionaryService(
            ILogger<ServiceBase> logger,
            IOptions<WmsSettings> options,
            IMapper mapper,
            IMenuRepository menuRepository,
            ISystemRepository systemRepository)
            : base(logger, options, mapper)
        {
            this.menuRepository = menuRepository;
            this.systemRepository = systemRepository;
        }

        public async Task<ActionResult<DictionaryDO>> GetDictionary(string menuId, UserInfo userInfo)
        {
            var result = new ActionResult<DictionaryDO>("获取数据字典");
            try
            {
                if (string.IsNullOrWhiteSpace(menuId))
                    return result.ArgumentError("菜单ID不能为空");

                var menuPO = await menuRepository.GetMenu(Convert.ToInt64(menuId));
                if (menuPO == null)
                    return result.DbError($"ID:{menuId},菜单数据未找到");

                var menuConfigDO = mapper.Map<MenuConfigDO>(menuPO);
                result = await GetDictionary(menuConfigDO, userInfo);
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }

        public async Task<ActionResult<DictionaryDO>> GetDictionary(MenuConfigDO? menuConfig, UserInfo userInfo)
        {
            var result = new ActionResult<DictionaryDO>("获取数据字典");
            try
            {
                if (menuConfig == null)
                    return result.ArgumentError("菜单数据不能为空");

                var data = new Dictionary<string, List<IdTextPair>>();
                foreach (var column in menuConfig.ColumnList)
                {
                    if ((column.ControlTypeCode == "ControlType_Select" || column.ControlTypeCode == "ControlType_MultiSelect") && !string.IsNullOrWhiteSpace(column.DataSource))
                    {
                        var getDictionaryResult = await GetDictionary(column.DataSource);
                        if (getDictionaryResult.IsSuccess)
                        {
                            data.Add(column.Field, getDictionaryResult.Data!);
                        }
                    }
                }

                result.Data = new DictionaryDO()
                {
                    Dictionary = data
                };
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }

        public async Task<ActionResult<DictionaryDO>> GetDictionaryType(UserInfo userInfo)
        {
            var result = new ActionResult<DictionaryDO>("获取数据字典");
            try
            {
                var getDictionaryResult = await GetDictionary("DIC:0");
                if (!getDictionaryResult.IsSuccess)
                    return result.Fail(getDictionaryResult);

                result.Data = new DictionaryDO()
                {
                    Dictionary = new Dictionary<string, List<IdTextPair>>()
                    {
                        { "0" , getDictionaryResult.Data! }
                    }
                };
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }

        private async Task<ActionResult<List<IdTextPair>>> GetDictionary(string dataSource)
        {
            var result = new ActionResult<List<IdTextPair>>();
            try
            {
                var list = dataSource.Split(";", StringSplitOptions.RemoveEmptyEntries & StringSplitOptions.TrimEntries);
                var sql = list[0].Trim();
                var data = new List<IdTextPair>();
                if (sql.StartsWith("DIC:", StringComparison.InvariantCultureIgnoreCase))
                {
                    var typeCode = sql.Replace("DIC:", "").ToUpper();
                    var dictionaryPOList = await systemRepository.FindByCondition<DictionaryPO>(entity => entity.TypeCode.ToUpper() == typeCode);
                    data = dictionaryPOList.OrderBy(entity => entity.SortNumber).Select(entity => new IdTextPair()
                    {
                        Id = entity.Code,
                        Text = entity.Name
                    }).ToList();
                }
                else
                {
                    var dataTable = await systemRepository.ExecuteQuery(sql);
                    if (dataTable != null)
                    {
                        data = dataTable.AsEnumerable().Select(row => new IdTextPair()
                        {
                            Id = row["ID"].ToString()!,
                            Text = row["TEXT"].ToString()!,
                            BindFieldId = dataTable.Columns.Contains("BIND") ? row["BIND"].ToString() : "",
                        }).ToList();
                    }
                }

                result.Data = data;
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }
    }
}
